package com.example.myapplication;

import android.app.Notification;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;

import com.base.core.EmptyUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

public class NotificationMonitorService extends NotificationListenerService {

    // 在收到消息时触发
    public static String pakage = "";
    public static List<String> allpakage = new ArrayList<>();

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {

        Bundle extras = sbn.getNotification().extras;

        // 获取接收消息APP的包名
        String notificationPkg = sbn.getPackageName();
//        if ("com.android.mms.service".equals(notificationPkg)) { //短信
//            NoticeBean event = new NoticeBean();
//            event.setType(-2);
//            EventBus.getDefault().post(event);
//            return;
//        }
        if (!allpakage.contains(notificationPkg)) {
            return;
        }
        // 获取接收消息的抬头
        String notificationTitle = extras.getString(Notification.EXTRA_TITLE);

        // 获取接收消息的内容

        String notificationText = extras.getString(Notification.EXTRA_TEXT);
        String subtext = extras.getString(Notification.EXTRA_SUB_TEXT);
        String bigtext = extras.getString(Notification.EXTRA_BIG_TEXT);
        if (EmptyUtils.isEmpty(notificationText)) {
            notificationText = subtext;
        }
        if (EmptyUtils.isEmpty(notificationText)) {
            notificationText = bigtext;
        }
        if (EmptyUtils.isEmpty(notificationText)) {
            notificationText = extras.toString();
        }

        Log.i("NotificationInfo",
                " Notification posted " + notificationTitle + " & " + notificationText + "&" + notificationPkg);
        NoticeBean bean = new NoticeBean();
        bean.setType(1);
        bean.setTitle(notificationTitle);
        bean.setTime(System.currentTimeMillis());
        bean.setNoticeContent(notificationText);
        bean.setNotificationPkg(notificationPkg);
        EventBus.getDefault().post(bean);
    }


// 在删除消息时触发

    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {


        Bundle extras = sbn.getNotification().extras;

        // 获取接收消息APP的包名

        String notificationPkg = sbn.getPackageName();

        // 获取接收消息的抬头

        String notificationTitle = extras.getString(Notification.EXTRA_TITLE);

        // 获取接收消息的内容

        String notificationText = extras.getString(Notification.EXTRA_TEXT);

        Log.i("NotificationInfo",
                " Notification removed " + notificationTitle + " & " + notificationText);

    }

}

